const DataLoader = require('dataloader')
import { User, Answer, UserGroup } from '../../models'
import { placeData, groupData } from '../../lib/graphql'
import fdb from '../../lib/fdb'
import _ from 'lodash'

export const userLoader = () =>
  new DataLoader(
    async keys => {
      let data = await User.findAll({ where: { id: { $in: keys } } })
      return placeData(keys, data, 'id')
    },
    { cacheKeyFn: key => key.toString() }
  )

export const memberLoader = () =>
  new DataLoader(
    async keys => {
      let gids = []
      let uids = []
      keys.forEach(n => {
        let t = n.split('_')
        gids.push(t[0])
        uids.push(t[1])
      })
      let data = await UserGroup.findAll({ where: { groupId: { $in: gids }, userId: { $in: uids } } })
      let kData = _.keyBy(data, n => {
        return n.groupId + '_' + n.userId
      })
      let placeData = []
      keys.forEach(n => {
        if (!kData[n]) placeData.push(null)
        placeData.push(kData[n])
      })
      return placeData
    },
    { cacheKeyFn: key => key.toString() }
  )

export const userLoaderByDocumentAnswer = () =>
  new DataLoader(
    async keys => {
      let data = await Answer.findAll({
        where: { documentId: { $in: keys } },
        group: ['documentId', 'userId'],
        order: [['updatedAt', 'DESC']]
      })
      let users = []
      for (let i = 0; i < data.length; i++) {
        users.push(
          Object.assign({ documentId: data[i].documentId }, data[i].userInfo)
        )
      }
      return groupData(keys, users, 'documentId')
    },
    { cacheKeyFn: key => key.toString() }
  )
